package com.easemob.helpdesk.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;

import android.text.InputFilter;
import android.text.TextUtils;
import android.text.method.NumberKeyListener;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

//import com.bigkoo.pickerview.builder.TimePickerBuilder;
//import com.bigkoo.pickerview.listener.OnTimeSelectListener;
//import com.bigkoo.pickerview.view.TimePickerView;
//import com.bigkoo.pickerview.builder.TimePickerBuilder;
//import com.bigkoo.pickerview.listener.OnTimeSelectListener;
//import com.bigkoo.pickerview.view.TimePickerView;
//import com.easemob.helpdesk.activity.PreviewImageActivity;
//import com.easemob.helpdesk.bean.IDCardInfo;
//import com.easemob.helpdesk.bean.SubmitSuccessBean;
//import com.easemob.helpdesk.bean.UploadFileBean;
//import com.easemob.helpdesk.utils.IDCardUtils;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.easemob.helpdesk.bean.IDCardVerifyResultBean;
import com.easemob.helpdesk.utils.Base64Utils;
import com.easemob.helpdesk.utils.FileUtils;
import com.easemob.helpdesk.utils.ImageResizer;
import com.facebook.common.executors.UiThreadImmediateExecutorService;
import com.housekeeperapp.R;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;
//import com.tbruyelle.rxpermissions2.Permission;
//import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiaolong.wei on 2019/1/11.
 */

public class IDCardVerifyStepOneActivity extends BaseActivityV2 implements View.OnClickListener {

    public static final String MIME_TYPE = "multipart/form-data";
    private static final String TAG = "IDCardVerifyActivity";
    private static final int REQUEST_TAKE_PHOTO_CODE = 1001;
    private static final int REQUEST_CODE_REQUEST_PERMISSIONS = 2001;
    private static final int REQUEST_CODE_ALERT_DIALOG_ACCESS = 3001;
    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.back){
            finish();
        }else if(view.getId()==R.id.id_card_front_place_holder_layout){
            checkPermission();
        }
        else if(view.getId()==R.id.id_card_front_image){
        }
        else if(view.getId()==R.id.clear_front_image){
            clearImage();
        }
        else if(view.getId()==R.id.submit){
            if (System.currentTimeMillis() - clickTime < 1000){//防止双击
                return;
            }
            if (isClickable){
                isClickable = false;
                submit();
            }

            clickTime = System.currentTimeMillis();
        }
    }
    View back;
    @Override
    protected void initFindView() {
        super.initFindView();
        back=findViewById(R.id.back);
        back.setOnClickListener(this);
        contentView=findViewById(R.id.content_view);
        titleBar=findViewById(R.id.title_bar);


        nameInput=findViewById(R.id.name_input);
        idCardInput=findViewById(R.id.id_card_input);
        userPhoto=findViewById(R.id.id_card_front_image);
        userPhotoPlaceHolderLayout=findViewById(R.id.id_card_front_place_holder_layout);
        userPhotoPlaceHolderLayout.setOnClickListener(this);
        userPhotoLayout=findViewById(R.id.id_card_front_layout);

        submit=findViewById(R.id.submit);
        submit.setOnClickListener(this);
        mProgressBarLayout=findViewById(R.id.progressBar_layout);
        mProgressBar=findViewById(R.id.progressBar);
        mClearUserPhoto=findViewById(R.id.clear_front_image);
        mClearUserPhoto.setOnClickListener(this);
        uploadText=findViewById(R.id.upload_text);
    }

    View contentView;
    View titleBar;
    EditText nameInput;
    EditText idCardInput;
    ImageView userPhoto;
    FrameLayout userPhotoPlaceHolderLayout;
    FrameLayout userPhotoLayout;
    TextView submit;
    FrameLayout mProgressBarLayout;
    ProgressBar mProgressBar;
    View mClearUserPhoto;
    TextView uploadText;
    Uri mUri;
    Bitmap userPhotoBm;
    private String photoBase64;
    private String mPhotoPath;
    //参数
    private String idCardName;
    private String idCardNumber;
    File mFile;

    private long clickTime;
    private PhotoHandler mHandler;
    private Toast toast;
    private boolean isClickable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.id_card_verify_step_one_layout);
        initFindView();
        initView();
        isClickable = true;

    }

    private void initView(){
        nameInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(8)});
        idCardInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(18)});
        idCardInput.setKeyListener(new NumberKeyListener() {
            @Override
            public int getInputType() {
                return android.text.InputType.TYPE_CLASS_PHONE;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] numberChars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'x','X' };
                return numberChars;
            }
        });

        mProgressBarLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
    }

    private void showLoading(){
        mProgressBarLayout.setVisibility(View.VISIBLE);
    }
    private void hideLoading(){
        mProgressBarLayout.setVisibility(View.GONE);
    }


//    @OnClick({R.id.back,  R.id.id_card_front_place_holder_layout,R.id.id_card_front_image,R.id.clear_front_image, R.id.submit})
//    public void onViewClicked(View view) {
//
//
//        switch (view.getId()) {
//            case R.id.back:
//                finish();
//                break;
//            case R.id.id_card_front_place_holder_layout:
//                checkPermission();
//                break;
//            case R.id.id_card_front_image:
//                break;
//            case R.id.clear_front_image:
//                clearImage();
//                break;
//            case R.id.submit:
//                if (System.currentTimeMillis() - clickTime < 1000){//防止双击
//                    return;
//                }
//                if (isClickable){
//                    isClickable = false;
//                    submit();
//                }
//
//                clickTime = System.currentTimeMillis();
//                break;
//        }
//    }

    private void hideInputMethod(){
        InputMethodManager imm =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                    0);
        }
    }

    private boolean verifyData(){
        idCardName = nameInput.getText().toString();
        if (TextUtils.isEmpty(idCardName)){
            showToast("请输入姓名");
            isClickable = true;
            return false;
        }
        if (idCardName.length() > 8){
            showToast("请输入正确的姓名");
            isClickable = true;
            return false;
        }
        idCardNumber = idCardInput.getText().toString();
        if (TextUtils.isEmpty(idCardNumber)){
            showToast("请输入身份证号");
            isClickable = true;
            return false;
        }
        if (idCardNumber.length() != 18){
            showToast("身份证号格式错误，请重新输入");
            isClickable = true;
            return false;
        }

        if (TextUtils.isEmpty(mPhotoPath)){
            showToast("请上传人脸照片");
            isClickable = true;
            return false;
        }

        if (userPhotoBm == null){
            showToast("请上传患者正面人脸照片");
            isClickable = true;
            return false;
        }



        Log.d(TAG, "verifyData: t="+MainActivity.ticket);
        Log.d(TAG, "verifyData: idCardName="+idCardName);
        Log.d(TAG, "verifyData: idCardNumber="+idCardNumber);
        Log.d(TAG, "verifyData: photoBase64="+photoBase64);

        if (!photoBase64.startsWith("base64://")){
            photoBase64 = "base64://"+photoBase64;
        }


        return  true;

    }
    private void submit(){
        if (verifyData()){
            showLoading();
            postData();
//            Intent intent = new Intent(this,IDCardVerifyStepTwoActivity.class);
//            intent.putExtra("ID_CARD_NAME",idCardName);
//            intent.putExtra("ID_CARD_NUM",idCardNumber);
//            intent.putExtra("PHOTO_PATH",mPhotoPath);
//            startActivity(intent);
        }
    }

    private void showToast(String msg){
        if (toast == null){
            toast = Toast.makeText(IDCardVerifyStepOneActivity.this,msg,Toast.LENGTH_SHORT);
        }
        toast.setText(msg);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void postData(){
        ApiService service = HKHttpUtils.getApiService();
        service.idCardCheck(MainActivity.ticket,idCardName,idCardNumber,photoBase64,"","").enqueue(new HKResponseResultCallBack<IDCardVerifyResultBean>() {
            @Override
            public void onSuccess(IDCardVerifyResultBean idCardVerifyResultBean) {
                hideLoading();
                if (idCardVerifyResultBean != null) {
                    if (idCardVerifyResultBean.isSuccess()) {
                        IDCardVerifyResultBean.DataBean data = idCardVerifyResultBean.getData();
                        if (data != null){
                            IDCardVerifyResultBean.DataBean.VerifyStatusBean verifyStatus = data.getVerifyStatus();
                            if (verifyStatus != null){
                                if (verifyStatus.getStatusCode() == 1 && verifyStatus.getAuthorityComparisonScore() >= 95){
                                    showToast("认证成功");
                                    mHandler.sendEmptyMessageDelayed(2,3000);
                                    return;
                                }else{
                                    showToast(TextUtils.isEmpty(verifyStatus.getAuditConclusions())?"请重新拍摄":verifyStatus.getAuditConclusions());
                                    isClickable = true;
                                    return;
                                }
                            }
                        }
                        showToast("认证不通过");
                        isClickable = true;
                    } else {
                        showToast(TextUtils.isEmpty(idCardVerifyResultBean.getMessage())?idCardVerifyResultBean.getMessage():"认证不通过");
                        isClickable = true;
                    }
                }else {
                    showToast("认证失败");
                    isClickable = true;
                }
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                hideLoading();
                showToast(msg);
                isClickable = true;
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                hideLoading();
                showToast("网络连接异常");
                isClickable = true;

            }
        });

    }

    private void clearImage(){
        userPhoto.setImageDrawable(null);
        mClearUserPhoto.setVisibility(View.GONE);
        userPhoto.setVisibility(View.GONE);
        userPhotoPlaceHolderLayout.setVisibility(View.VISIBLE);
        userPhotoBm = null;
        mPhotoPath = "";
    }

    private void checkPermission(){

        int hasWritePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int hasTakePhotoPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA);
        if (hasWritePermission != PackageManager.PERMISSION_GRANTED && hasTakePhotoPermission != PackageManager.PERMISSION_GRANTED){
            PermissionGen.with(this)
                    .addRequestCode(REQUEST_CODE_REQUEST_PERMISSIONS)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                    .request();
        } else if (hasTakePhotoPermission != PackageManager.PERMISSION_GRANTED){
            PermissionGen.with(this)
                    .addRequestCode(REQUEST_CODE_REQUEST_PERMISSIONS)
                    .permissions(Manifest.permission.CAMERA)
                    .request();
        } else if (hasWritePermission != PackageManager.PERMISSION_GRANTED ){
            PermissionGen.with(this)
                    .addRequestCode(REQUEST_CODE_REQUEST_PERMISSIONS)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .request();
        }else {
            takePhoto();
        }
    }




    private void takePhoto(){

        try {
            mFile = FileUtils.createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        Log.d(TAG, "takePhoto: "+mFile.getAbsolutePath());
         mUri =null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //Android 7.0及以上获取文件 Uri
            mUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()+".provider", mFile);
        } else {
            //获取文件Uri
            mUri = Uri.fromFile(mFile);
        }
        //调取系统拍照
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO_CODE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_TAKE_PHOTO_CODE) {//获取系统照片上传
            Log.d(TAG, "onActivityResult:user photo is: "+mUri);
            String uriPath = mUri.getPath();
            if (TextUtils.isEmpty(uriPath)){
                Log.e(TAG, "onActivityResult: ",new Throwable("照片文件不存在！"));
                return;
            }
            showLoading();
            if (mHandler == null){
                mHandler = new PhotoHandler(this);
            }
            mPhotoPath = Environment.getExternalStorageDirectory()+uriPath.split("external_files")[1];

            new Thread(new Runnable() {
                @Override
                public void run() {
                    userPhotoBm  = ImageResizer.decodeBitmapFromUri(IDCardVerifyStepOneActivity.this,280,210,mUri, 2*1024);
                    Log.d(TAG, "run:----------- "+userPhotoBm.getByteCount());
                    photoBase64 = Base64Utils.bitmapToBase64(userPhotoBm);
                    if (TextUtils.isEmpty(photoBase64)) {
                        mHandler.sendEmptyMessage(0);
                    } else {
                        mHandler.sendEmptyMessage(1);
                    }
                }
            }).start();

        }
    }


    public void updatePhoto(){
        if (userPhotoBm != null) {
            Log.d(TAG, "updatePhoto: --------size = "+userPhotoBm.getByteCount());
            if (mFile.exists()){
                Glide.with(this).load(mUri).into(userPhoto);
                mClearUserPhoto.setVisibility(View.VISIBLE);
                userPhoto.setVisibility(View.VISIBLE);
                userPhotoPlaceHolderLayout.setVisibility(View.GONE);
            }
        }
    }

//    private MultipartBody.Part packFileParam(File file){
//        RequestBody requestBody = RequestBody.create(MediaType.parse(MIME_TYPE),file);
//        MultipartBody.Part part = MultipartBody.Part.createFormData("file",file.getName(),requestBody);
//        return part;
//    }

//    private void uploadFile(MultipartBody.Part file, RequestBody type,final Bitmap bm){
//
//        ApiService apiService = HKHttpUtils.getApiService();
//        apiService.uploadFile(file,type).enqueue(new HKResponseResultCallBack<UploadFileBean>() {
//            @Override
//            public void onSuccess(UploadFileBean uploadFileBean) {
//                Log.d(TAG, "onSuccess: ");
//                String s = "";
//                if (uploadFileBean != null){
//                    Gson gson = new Gson();
//                    s = gson.toJson(uploadFileBean);
//                }
//                if ("front".equals(frontOrBack)){
//                    uploadFileFront = uploadFileBean;
//                    userPhotoUploadFileJson = s;
//                    mIdCardFrontImage.setImageBitmap(bm);
//                    mIdCardFrontPlaceHolderLayout.setVisibility(View.GONE);
//                }else {
//                    uploadFileBack = uploadFileBean;
//                    backUploadFileJson = s;
//                    mIdCardBackImage.setImageBitmap(bm);
//                    mIdCardBackPlaceHolderLayout.setVisibility(View.GONE);
//                }
//                hideLoading();
//            }
//
//            @Override
//            public void onGetDataFailed(int cd, String msg) {
//                Log.d(TAG, "onGetDataFailed: "+msg);
//                hideLoading();
//                Toast.makeText(IDCardVerifyStepOneActivity.this,msg,Toast.LENGTH_LONG).show();
//            }
//
//            @Override
//            public void onFailed(Call call, Throwable t) {
//                hideLoading();
//                Log.d(TAG, "onFailed: ");
//
//            }
//        });
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = REQUEST_CODE_REQUEST_PERMISSIONS)
    public void storageAuthSuccess(){
        takePhoto();
    }

    @PermissionFail(requestCode = REQUEST_CODE_REQUEST_PERMISSIONS)
    public void storageAuthFail(){
        new AlertDialog.Builder(this).setMessage("app需要读写手机存储权限 \n请在权限管理->读写手机存储->设为允许!").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }
        }).create().show();

    }

    public void onSuccess() {
        updatePhoto();
        hideLoading();
    }

    public void onFailure() {
        showToast("解析转码患者人脸照失败");
//        Toast.makeText(this,"解析转码患者人脸照失败！",Toast.LENGTH_LONG);
        hideLoading();
    }



    public static class PhotoHandler extends Handler {
        private WeakReference<IDCardVerifyStepOneActivity> weakReference;

        public PhotoHandler(IDCardVerifyStepOneActivity activity) {
            this.weakReference = new WeakReference<IDCardVerifyStepOneActivity>(activity);

        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            IDCardVerifyStepOneActivity activity = weakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        activity.onSuccess();
                        break;
                    case 0:

                        activity.onFailure();
                        break;
                    case 2:
                        activity.finish();
                        break;
                    default:

                }
            }
        }
    }
}
